package com.sharecode.stock.controller;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.sharecode.stock.service.UserService;
import com.sharecode.stock.thread.ThreadLocalUtils;
import com.sharecode.stock.vo.User;

@RestController
@RequestMapping("/api")
@ControllerAdvice
public class LoginController {

	@Autowired
	private UserService userService;

	@PostMapping("user/login")
	public Object login(@RequestBody JSONObject json) {
		String username = json.getString("username");
		String password = json.getString("password");

		User user = userService.login(username, password);

		Map<String, String> map = new HashMap<>();
		map.put("token", UUID.randomUUID().toString());
		ThreadLocalUtils.getRequest().getSession().setAttribute("user", user);
		return map;
	}

	@GetMapping("user/info")
	public Object userInfo() {
		JSONObject json = new JSONObject();
		json.put("introduction", "I am a super administrator");
		json.put("avatar", "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
		json.put("name", "Super Admin");
		json.put("roles", Arrays.asList("admin"));
		return json;
	}

	@PostMapping("user/logout")
	public void logout() {
		ThreadLocalUtils.getRequest().getSession().removeAttribute("user");
	}

}
